#include "Col.ph"
#ifdef __GNUG__
#pragma implementation
#endif

#include "FileBuf.h"
#include "File.h"

//---- FileBuf -----------------------------------------------------------------

Filebuf::Filebuf() : StreamBuf(0)
{
	fd= -1;
	opened= FALSE;
}

Filebuf::Filebuf(int nfd) : StreamBuf(0)
{
	fd= nfd;
	opened= TRUE;
}

Filebuf::Filebuf(int nfd, char* p, int l) : StreamBuf(l, p)
{
	fd= nfd;
	opened= TRUE;
}

Filebuf::Filebuf(const char* name, open_mode om) : StreamBuf(0)
{
	opened= FALSE;
	open(name, om);
}

Filebuf::~Filebuf()
{
	close();
}

Filebuf* Filebuf::open(const char *name, open_mode om)
{
	const char *where= "Filebuf::open";
	close();

	fpos= 0;
	switch (om) {
	case input:
		fd= File::Open(name, 0, where);
		break;
	case output:
		fd= File::Creat(name, 0664, where);
		break;
	case append:
		fd= File::Open(name, 1, where);
		if (fd < 0)
			fd= File::Creat(name, 0664, where);
		if (fd >= 0)
			fpos= File::Lseek(fd, 0, 2);
		break;
	}

	if (fd < 0) {
		opened= FALSE;
		return 0;
	}

	if (base == 0)
		setbuf(0, BUFSIZE);

	opened= TRUE;
	return this;
}

bool Filebuf::close()
{
	if (opened) {
		if (fd > 2)
			File::Close(fd, "Filebuf::close");
		opened= FALSE;
		return TRUE;
	}
	return FALSE;
}

int Filebuf::Overflow(u_char *bp, int n)
{
	if (opened)
		return File::Write(fd, (char*)bp, n);
	return EOF;
}

int Filebuf::Underflow(u_char *p, int n)
{
	if (!opened)
		return EOF;
	return File::Read(fd, (char*)p, n);
}

long Filebuf::Seek(long pos, int whence)
{
	return File::Lseek(fd, pos, whence);
}

